package dao

import (
	"errors"
	"time"

	"github.com/segmentio/ksuid"
)

type TaskMountedCron struct {
	ID      string `json:"id" xorm:"pk notnull unique 'id'"`
	Created int64  `json:"created" xorm:"'created'"`
	Deleted int    `json:"deleted" xorm:"'deleted'"`
	Tid     string `json:"tid" xorm:"'tid'"`
	Cid     string `json:"cid" xorm:"'cid'"`
}

func (c *TaskMountedCron) Add() error {
	if c.Tid == "" || c.Cid == "" {
		return errors.New("tid和cid不能为空")
	}
	tmc := TaskMountedCron{}
	if bol, err := localdb.Where("cid=? and tid=?", c.Cid, c.Tid).Get(&tmc); err != nil {
		return err
	} else {
		if bol {
			return nil
		}
	}
	c.ID = ksuid.New().String()
	c.Created = time.Now().Unix()
	c.Deleted = 0
	if _, err := localdb.Insert(c); err != nil {
		return err
	}
	return nil
}

func AddTaskMountedCron(tid string, crontabs ...string) error {
	if _, err := localdb.Where("tid=?", tid).Delete(new(TaskMountedCron)); err != nil {
		return err
	}
	for _, v := range crontabs {
		tmc := new(TaskMountedCron)
		tmc.Tid = tid
		tmc.Cid = v
		if err := tmc.Add(); err != nil {
			return err
		}
	}
	return nil
}
